#!/usr/bin/env python
# encoding: utf-8
"""
group_compare.py

Created by Bud Gibson on 2010-05-30.
Copyright (c) 2010 Algorithmic Advertising. All rights reserved.
"""

def set_of_ids(group):
  """Gets a set of IDs for a group"""
  return set([g1['id'] for g1 in group])

def group_intersection(group1,group2):
  """Returns the stub list of people in both groups"""
  group1_ids = set_of_ids(group1)
  group2_ids = set_of_ids(group2)
  intersection = group1_ids & group2_ids
  return [inter for gid in intersection for inter in group1 if inter['id'] == gid]

def group_difference(group1,group2):
  """Returns the group of people in group1 but not in group2"""
  group1_ids = set_of_ids(group1)
  group2_ids = set_of_ids(group2)
  difference = group1_ids - group2_ids
  return [diff for gid in difference for diff in group1 if diff['id'] == gid]
  
def group_union(group1,group2):
  """Gives the union of groups 1 and 2"""
  return group_intersection(group1,group2) + group_difference(group1,group2) + group_difference(group2,group1)

def group_non_reciprocator(group1,group2):
  """Produces a subset of group1 that is not also a member of group2"""
  reciprocator = group_intersection(group1,group2)
  non_reciprocator = group_difference(group1,reciprocator)
  return non_reciprocator

def group_in_out_labeled(group1,group2,inLabel='ingroup',outLabel='outgroup'):
  """Labels whether members of group1 are also in group2 using the values for inLabel and outLabel"""
  inGroup = group_intersection(group1,group2)
  for ig in inGroup:
    ig['groupLabel'] = inLabel
  outGroup = group_difference(group1,inGroup)
  for ig in outGroup:
    ig['groupLabel'] = outLabel
  return inGroup + outGroup

def main():
  try:
    from buzztracker.REST.poco_public import followed_by, followers_of
  except ImportError:
    import sys
    import os
    sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
    from buzztracker.REST.poco_public import followed_by, followers_of
  import pprint
  print set_of_ids([])
  pp = pprint.PrettyPrinter(depth=4)
  fling = followed_by('fpgibson')
  flrs = followers_of('fpgibson')
  intersection = group_intersection(fling,flrs)
  difference = group_difference(fling,intersection)
  pp.pprint(difference)
  labeled = group_in_out_labeled(fling,flrs)
  pp.pprint(group_non_reciprocator(fling,flrs))
  print 'followers:', len(flrs)
  print 'following:', len(fling)
  print len(group_intersection(fling,flrs))
  print len(group_difference(fling,flrs))
  print len(group_difference(flrs,fling))
  print len(group_union(fling,flrs))


if __name__ == '__main__':
  main()

